<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色列表按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item1, index) in scope.row.children" :key="item1.id" :class="[ 'bdbottom', index === 0 ? 'bdtop' : '', 'vcenter']">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="icon el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过 for 循环 嵌套渲染二级权限 -->
                <el-row v-for="(item2, index) in item1.children" :key="item2.id" :class="[ index === 0 ? '' : 'bdtop', 'vcenter']">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="icon el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope='scope'>
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRoleUser(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoleUser(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="assignPermissions(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 提示添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="50%"
        @close="resetForm('ruleForm')">
        <!-- 内容主体区域 -->
        <el-form :model="addRuleForm" :rules="addRules" ref="ruleForm" label-width="100px" >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRuleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRuleForm.roleDesc"></el-input>
          </el-form-item>
          <!-- 内容主体按钮 -->
        </el-form>
        <span slot="footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRoleList">确 定</el-button>
          </span>
      </el-dialog>

      <!-- 提示编辑用户对话框 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="editVisibile"
        width="50%"
        @close="resetForm('editForm')">
          <!-- 内容主体区域 -->
          <el-form :model="editRoleList" :rules="addRules" ref="editForm" label-width="100px">
            <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRoleList.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRoleList.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 内容主体按钮 -->
        <span slot="footer">
            <el-button @click="editVisibile = false">取 消</el-button>
            <el-button type="primary" @click="editRoleListCommit(editRoleList.roleId)">确 定</el-button>
          </span>
      </el-dialog>

      <!-- 添加用户权限对话框 -->
      <el-dialog
        title="添加权限"
        :visible.sync="assignPermissionsVisibile"
        width="50%"
        @close="setRightDialogClosed">
        <!-- 树形控件 -->
        <el-tree
          :data="assignPermissionsList"
          :props="treeProps"
          show-checkbox node-key="id"
          default-expand-all
          ref="treeRef"
          :default-checked-keys="defKeys"></el-tree>
        <!-- 内容主体按钮 -->
        <span slot="footer">
            <el-button @click="assignPermissionsVisibile = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
          </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      roleList: [],
      // 添加用户对话框是否显示
      dialogVisible: false,
      // 添加用户信息
      addRuleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加用户校验
      addRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在2到5个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在2到8个字符', trigger: 'blur' }
        ]
      },
      // 编辑用户对话框是否显示
      editVisibile: false,
      // 编辑用户对话框需要的信息
      editRoleList: {},
      // 添加权限对话框是否显示
      assignPermissionsVisibile: false,
      // 树形权限的数据
      assignPermissionsList: [],
      // 树形控件绑定的数据对象
      treeProps: {
        // 显示的文本
        label: 'authName',
        // 绑定的数据源
        children: 'children'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      // 因为分配权限对话框拿不到id，先保存起来
      roleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取所有的角色列表
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败!')
      }
      this.roleList = res.data
      console.log(this.roleList)
    },
    // 发送网络请求，添加新用户
    addRoleList() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('roles', this.addRuleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败！')
        }
        this.$message.success('添加新用户成功！')
        this.getRoleList()
        this.dialogVisible = !this.dialogVisible
      })
    },
    // 清除对话框的值
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 编辑角色修改信息
    async editRoleUser(id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      this.editRoleList = res.data
      this.editVisibile = true
      // console.log(this.editRoleList)
    },
    // 确定编辑修改用户信息，发送网络请求
    editRoleListCommit(id) {
      this.$refs.editForm.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(`roles/${id}`, {
          roleName: this.editRoleList.roleName,
          roleDesc: this.editRoleList.roleDesc
        })
        if (res.meta.status !== 200) {
          this.$message.error('修改用户数据失败，请重新提交数据！')
        }
        this.$message.success('修改用户数据成功！')
        this.getRoleList()
        this.editVisibile = !this.editVisibile
      })
    },
    // 根据 id 删除用户
    async deleteRoleUser(id) {
      const removeResult = await this.$confirm('是否确认删除此用户？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warnsing'
      }).catch(err => {
        return err
      })
      if (removeResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.info('删除用户失败，请稍后重试')
      }
      this.$message.success('删除用户数据成功！')
      this.getRoleList()
    },
    // 根据 id 删除用户权限
    async removeRightById(role, rightId) {
      const removeResult = await this.$confirm('是否确认删除此权限？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warnsing'
      }).catch(err => {
        return err
      })
      if (removeResult !== 'confirm') {
        return this.$message.info('已取消删除权限')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      role.children = res.data
    },
    // 根据id 获取用户所有树形权限
    async assignPermissions(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.warning('获取用户权限失败！')
      }
      this.assignPermissionsList = res.data
      console.log(this.assignPermissionsList)

      // 获取三级节点的id
      this.getDefKeys(role, this.defKeys)

      this.assignPermissionsVisibile = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到defKeys上
    getDefKeys(node, arr) {
      // 如果当前node节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getDefKeys(item, arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRoleList()
      this.assignPermissionsVisibile = false
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }
  .bdtop {
    border-top: 1px solid #ccc;
  }
  .bdbottom {
    border-bottom: 1px solid #ccc;
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
